<?php
  require_once PATH_CLASS.'session.class.php';
  require_once PATH_CLASS.'membre.class.php';
  require_once PATH_CLASS.'membre.class.php';
//  require_once PATH_LIB.'smarty/Smarty.class.php';
  
/**
 * Description of commun
 *
 * @author jpsiffert
 */
class commun extends base{
  const _LOGIN      = '__l';
  const _PWD        = '__p';
  const _REMEMBER   = '__r';
  const _LOGOUT     = '__o';
  const _COOKIEID   = 'loliUser';
  const _OUT_MEMBER = 'logOutMember';
  
  private static $_notifs = array();
  private static $_smartyCaching = true;

  
  /**
   *  retourne si on est en mode debug ou non
   * @return bool 
   */  
  public static function isDebug(){
    return DEBBUG;
  }
  
  public static function setcookie($name ,$value,$expire=0,$path='/',$domain='.association-lolita.com',$secure=false ,$httponly=false){
    if(self::isLocal()){
      $domain = 'localhost';
    }
    setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
  }
  
  public static function resetcookie($name,$expire=0,$path='/',$domain='.association-lolita.com',$secure=false ,$httponly=false){
    if(self::isLocal()){
      $domain = 'localhost';
    }
    setcookie($name, null, time()-10, $path, $domain, $secure, $httponly);
  }
  
  /**
   *  retourne si on est en developpement local ou non
   * @return bool 
   */
  public static function isLocal(){
    return LOCAL;
  }
  
  public static function isLogged(){
    $ret = session::get('isLogged');
    return $ret;
  }
  
  public static function setLogged(){
    return session::set('isLogged',true);
  }

  public static function setLogout(){
    return session::set('isLogged',false);
  }

  public static function setLoggedMembre(membre $membre){
    return session::set('membre',$membre);
  }
  
  public static function clearLoggedMembre(){
    return session::set('membre',null);
  }
  
  /**
   * return logged member object
   * @return membre
   */
  public static function getLoggedMembre(){
    return session::get('membre');
  }

  public static function getLoggedMembreId(){
    $membre = session::get('membre');
    $id = $membre instanceof membre ? $membre->membre_id : null;
    return $id;
  }
  
  
  
  public static function addNotif($notif){
    if(!is_array($notif)){
      $notif = array($notif);
    }
    
    foreach($notif as $key=>$value){
      self::$_notifs[]=$value;
    }
  }

  public static function getNotifs(){
    return self::$_notifs;
  }
  
  /**
   *
   * @param string $what
   * @return string 
   */
  public static function getHash($what){
    $hash = md5(GRAIN_DE_SABLE.$what.GRAIN_DE_SABLE);
    return $hash;
  }
  
  public static function getNewHash($len=0){
    $hash = md5(GRAIN_DE_SABLE.mt_rand().GRAIN_DE_SABLE);
    
    if($len<>0 && strlen($hash)>=$len){
      $hash = substr($hash, 0, $len);
    }
    
    return $hash;
  }
  
  public static function getNewPwd($length=8){
    $ret='';
    $tryCnt=0;
    do{
      $chr=chr(mt_rand(ord('#'), ord('z')));
      
//      if(strpos('`;/_\\\'"]\[& ', $chr)===FALSE){
//      if(preg_match ("/[A-Za-z\d#@\+\$\*/\\:;,\?!]/", $chr)>0){
      if(preg_match ("/[A-Za-z\d\/#!%:]/", $chr)>0){
        switch($chr){
          case 'I': $chr='i';
          case 'l': $chr='L';
        }
        $ret.=$chr;
        $tryCnt=0;
      }
    } while (strlen($ret)<$length && ++$tryCnt<100);

    return $ret;
  }
  
  /**
   * @return string 
   */
  public static function getUid(){
    $id = str_replace(array('{','}'),'',com_create_guid());
    return $id;
  }

  public static function setSmartyCaching($st){
    self::$_smartyCaching = $st;
    return $st;
  }

  public static function getSmartyCaching(){
    return self::$_smartyCaching;
  }
  
  
/**
 * @param array $params
 * @return Smarty 
 */
  public static function getSmarty($params=array()){
    $default = array(
         'cache_dir'=>'./ztemp/cache'
        ,'compile_dir'=>'./ztemp'
        ,'tpl_path'=>PATH_TPL);
    $p = array_merge($default,$params);

    $smarty                 = new SmartyBC();
    
    $smarty->setTemplateDir($p['tpl_path']);
    $smarty->setCompileDir($p['compile_dir']);
    //$smarty->setConfigDir('/web/www.example.com/guestbook/configs/');
    $smarty->setCacheDir($p['cache_dir']);
    $smarty->setCompileCheck(true);

    
    if(LOCAL){
      $smarty->caching = self::getSmartyCaching();
      $smarty->cache_lifetime = 60;
    } else {
      $smarty->caching = self::getSmartyCaching();
      $smarty->cache_lifetime = 3600;
    }
    
    $smarty->caching = false;
    
    
        
//    $smarty->compile_check  = true;
//    $smarty->cache_dir      = $p['cache_dir'];
//    $smarty->caching        = false;
    if(SMARTY_DEBBUG){
      $smarty->debugging      = SMARTY_DEBBUG;
      Smarty_Internal_Debug::display_debug($smarty);
    }
//    $smarty->template_dir   =$p['tpl_path'];
//    $smarty->compile_dir    = $p['compile_dir'];
    $smarty->left_delimiter ='{';
    $smarty->right_delimiter='}';
    return $smarty;
  }

  /**
   * @param array $params
   * @return Smarty 
   */
  public static function getSmartyForMail($params=array()){
    $pars = array_merge($params,array('tpl_path'=>PATH_TPL.'/mails'));
    
    $mail = self::getSmarty($pars);
    
    return $mail;
  }

  public static function getSmartyFormulaire($params=array()){
    $pars = array_merge($params,array('tpl_path'=>PATH_TPL.'/mails'));
    
    $mail = self::getSmarty($pars);
    
    return $mail;
  }

  /**
   * @param array $params
   * @return Smarty 
   */
  public static function getSmartyPartial($params=array()){
    $pars = array_merge($params,array('tpl_path'=>PATH_TPL.'/__partials'));
    return self::getSmarty($pars);
  }
  
  /**
   * @param array $params
   * @return Smarty 
   */
  public static function getSmartyWidget($params=array()){
    $pars = array_merge($params,array('tpl_path'=>PATH_TPL.'/widgets'));
    return self::getSmarty($pars);
  }
  
  public static function getClassViewFromFile($__file__,$tpl_vars=array(),$explode1='php_page',$explode2='content.php'){
    
    if(!isset($__file__)){
      $__file__ = __FILE__;
    }
    
    $tb = explode($explode1,$__file__);
    
    if(isset($tb[1])){
      $path = explode($explode2, $tb[1]);
      $path = '.'.$path[0];
    } else {
      $path = $tb[0];
    }
    
    if($path){
      $tpl = $path.TPL_EXT;
      $ret = self::getClassView($tpl, $tpl_vars);
    }
    
    
    
    return $ret;

  }
  
  public static function getClassView($path,$tpl_vars=array()){
    $smarty = self::getSmarty();
    $smarty->assign($tpl_vars);
    $get = array2Obj($_GET);
    $smarty->assign('GET',$get);
    // set a separate cache_id for each unique URL
    $cache_id = md5($_SERVER['REQUEST_URI']);
    $ret = $smarty->fetch($path,$cache_id);
    return $ret;
  }
  
  public static function getDbLib($what,$id){
    
    $lib='';
    
    switch(strtolower($what)){
      case 'compet_lib':
        $lib = match::getCompetLib($id);
        break;
    }
    
    
    return $lib;    
  }

  public static function getSiteUrl(){
    return SITE_URL;
  }
  
  public static function signature($quelle=''){
    
    switch(strtolower($quelle)){
    case '' :
    case 'lolibot' :
      $ret="<em>Loli'Bot</em>";
      break;
    }
    
    return $ret;
  }  
  
  public static function bienvenueMembre($membre){
    $noms  = array('%surnom%','%prenom%','%prenom% %surnom% %nom%');
    $phrases = array(
       'Salut %s!'
      ,'Hey %s, ça fait du bien de te voir ^^'
      ,'Bonjour %s, bienvenue à bord!'
      ,'Hello %s!'
      ,'Ah te voilà enfin!'
      ,'Hey, mais qui voilà?'
      ,"Bref. C'est le retour de %s"
    );
    
    $idx    = array_rand($noms);
    $nom    = $noms[$idx];
    $idx    = array_rand($phrases);
    $phrase = $phrases[$idx];
    
    $ret = sprintf($phrase,$membre->link('',array('lib'=>$nom)));
    return $ret;
  }
  
  public static function auRevoirMembre($membre){
    $noms  = array('%surnom%','%prenom%','%prenom% %surnom% %nom%');
    $phrases = array(
       'You say goodbye, I say hello!'
      ,'Reviens nous vite %s'
      ,"J'ai fais quelque chose de mal?"
      ,'Bon allez, sans rancune %s?'
      ,'Au revoir, à bientôt.'
      ,'Tu sors!'
      ,"A la prochaine %s!"
      ,"Pars, et ne reviens <strong>JAMAIS!</strong><br />Mais non j'déconne!"
    );
    
    $idx    = array_rand($noms);
    $nom    = $noms[$idx];
    $idx    = array_rand($phrases);
    $phrase = $phrases[$idx];
    
    $ret = sprintf($phrase,$membre->link('',array('lib'=>$nom)));
    return $ret;
  }
  
  public static function doAutoLogin(){
    
    $isLogged = commun::isLogged();
    
    if(!$isLogged){
      if((isset($_REQUEST[self::_LOGIN]) && isset($_REQUEST[self::_PWD])) || isset($_COOKIE[self::_COOKIEID])){
        if((!empty($_REQUEST[self::_LOGIN]) && !empty($_REQUEST[self::_PWD])) || !empty($_COOKIE[self::_COOKIEID])){
          if(isset($_COOKIE[self::_COOKIEID])){
            $membre = membre::tryLogUserIn($_COOKIE[self::_COOKIEID], null ,$status);
            
            if($membre==null || $status==membre::LOG_NOT_FOUND){
              self::resetcookie(self::_COOKIEID);
              $_COOKIE[self::_COOKIEID]=null;
              $membre = membre::tryLogUserIn($_REQUEST[self::_LOGIN], $_REQUEST[self::_PWD],$status);
            }
            
          } else {
            $membre = membre::tryLogUserIn($_REQUEST[self::_LOGIN], $_REQUEST[self::_PWD],$status);
          }
          switch($status){
            case membre::LOG_NOT_FOUND:
              self::addNotif("Non, je te connais pas");
              break;
            case membre::LOG_FOUND:
              self::addNotif(self::bienvenueMembre($membre));
              self::setLogged();
              self::setLoggedMembre($membre);
              if(isset($_REQUEST[self::_REMEMBER])){
                $value = md5($membre->membre_email.$membre->membre_md5);
                self::setcookie(self::_COOKIEID, $value, time()+60*60*24*30,'/');
              }
              break;
          }
        }
      } 
    } else if(isset ($_REQUEST[self::_LOGOUT])){
        $membre = self::getLoggedMembre();
        session::set(self::_OUT_MEMBER,$membre);
        self::setLogout();
        self::clearLoggedMembre();
        self::resetcookie(self::_COOKIEID);
        
        header("Location: ".SITE_URL); 
        exit;
        
    }
    
    $membre = session::get(self::_OUT_MEMBER);
    if(isset($membre) && $membre instanceof membre){
      session::destroy(self::_OUT_MEMBER);
      self::addNotif(self::auRevoirMembre($membre));
      unset($membre);
    }
  }

  public static function DeleteFileOrDir($fileOrDir,$withMin=false){
    if($withMin && is_file($fileOrDir)){

      self::DeleteFileOrDir($fileOrDir);//delete the file itself
      $imgPars  = commun::getParamObj('images_size');
      $pathInfo = pathinfo($fileOrDir);
      $objVars  = get_object_vars($imgPars);
      foreach($objVars as $key=>$val){
        $file = $pathInfo['dirname']."/$key/".$pathInfo['basename'];
        self::DeleteFileOrDir($file);
      }

    } else {
      if(is_file($fileOrDir))
          $cmd='del';
      else if(is_dir($fileOrDir))
          $cmd='rmdir';

      $delete = @unlink($fileOrDir);
      if (file_exists($fileOrDir)) {
          $filesys = eregi_replace("/","\\",$fileOrDir);
          $delete = @system("$cmd $filesys");
          if (file_exists($fileOrDir)) {
              $delete = @chmod ($fileOrDir, 0775);
              $delete = @unlink($fileOrDir);
              $delete = @system("$cmd $filesys");
          }//end if (@file_exists($file))
      }//end if (@file_exists($file))

      return $delete;
    }
  }//end function DeleteFile($file)
  
  static function convertHTML(&$data){
    if(!is_array($data)){
      $data = htmlspecialchars($data, 0, 'UTF-8');
    } else {
      foreach ($data as $key => $value) {
        self::convertHTML($data[$key]);
      }
    }
  }  
  
  static function get_called_class($functionName=null)
  {
      $btArray = debug_backtrace();
      $btIndex = count($btArray) - 1;
      while($btIndex > -1)
      {
          if(!isset($btArray[$btIndex]['file']))
          {
              $btIndex--;
              if(isset($matches[1]))
              {
                  if(class_exists($matches[1]))
                  {
                      return $matches[1];
                  }
                  else
                  {
                      continue;
                  }
              }
              else
              {
                  continue;
              }
          }
          else
          {
              $lines = file($btArray[$btIndex]['file']);
              $callerLine = $lines[$btArray[$btIndex]['line']-1];
              if(!isset($functionName))
              {
                  preg_match('/([a-zA-Z\_]+)::/',
                  $callerLine,
                  $matches);
              }
              else
              {
                  preg_match('/([a-zA-Z\_]+)::'.$functionName.'/',
                      $callerLine,
                      $matches);
              }
              $btIndex--;
              if(isset($matches[1]))
              {
                  if(class_exists($matches[1]))
                  {
                      return $matches[1];
                  }
                  else
                  {
                      continue;
                  }
              }
              else
              {
                  continue;
              }
          }
      }
      return $matches[1];
  }  
  
  /**
   * @param type $params
   * @return Smarty
   */
  public static function getSmartyForm($params=array()){
    $pars = array_merge($params,array('tpl_path'=>PATH_TPL.'__partials/forms'));
    return self::getSmarty($pars);
  }

  public static function getParamObj($name){
    global $param;
    $json = '{}';

    if(!empty($param[$name])){
      $json = $param[$name];
    }

    return json_decode($json);
  }

  public static function isFrenchDate($date){
    $reg  = "/^(\d{2}).(\d{2}).(\d{2,4})$/";
    $ret  = false;
    if(preg_match($reg, $date)==1){
      $ret = preg_split("/[^\d]/", $date);
      if(count($ret)>=3 && checkdate($ret[1], $ret[0], $ret[2])){
        $ret=true;
      }
    }
    return $ret;
  }
  
  public static function gestionSousFiches(&$sql,$tableName,$keyName,$addCallback='',$deleteCallback='',$updateCallback=''){
    if(!is_array($sql)){
      $sql = array($sql);
    }
    
    $db = commun::getDb();
    if(isset($_POST['item'])){
      if(isset($_POST['item']['exist'])){
        foreach($_POST['item']['exist'] as $id=>$item){
            if(isset($item['checked'])){
                $sql[]=sprintf('DELETE FROM `%s` where `%s` = %d LIMIT 1',$tableName,$keyName,$id);
            }
            if($deleteCallback!=''){
              $ret = call_user_func($deleteCallback,$item,$id);
              if(trim($ret)!=''){
                $sql[]=$ret;
              }
            }
        }
      }

      if(isset($_POST['item']['add']) && isset($_POST['item']['add']['id'])){
        foreach($_POST['item']['add']['id'] as $i=>$item){
          if(isset($_POST['item']['add']['saison'])){
            $saison_id=$_POST['item']['add']['saison'][$i];

            if($saison_id==0 && isset($_POST['item']['add']['saison'][0])){
              $saison_id = $_POST['item']['add']['saison'][0];
            }

            if(isset($item) && $item!=0 && $saison_id!=0){
              if($addCallback!=''){
                $fields = call_user_func($addCallback,$item,$i,$saison_id);

                if(is_array($fields) && count($fields)>0){
                  $deleteWhere=array();
                  $update=array();
                  $sqlTmp=array();

                  foreach($fields as $field=>$value){
                    $valS = "'".DataBase::addslashes_sql($value)."'";
                    $deleteWhere[]="`$field`=$valS";
                    $update[0][] = $field;
                    $update[1][] = $valS;
                  }
                  try{
                    $sql[]=sprintf('DELETE FROM `%s` where %s',$tableName,join(' AND ',$deleteWhere));
                    $sql[]=sprintf('INSERT INTO `%s` (%s) values(%s)',$tableName,join(',',$update[0]),join(',',$update[1]));
                  } catch(Exception $e){
                    $msg  = $e->getMessage();
                  }

                }
              }
            }
          }
        }
      }

      $db->Update(implode(';',$sql));
    }
  }
  
  public static function dateToEtad($date){
    $ret=" ";
    if(self::isFrenchDate($date)){
      $ret = preg_split("/[^\d]/", $date);
      $dt  = new DateTime();
      $dt->setDate($ret[2], $ret[1], $ret[0]);
      $ret = $dt->format("Y-m-d");
    }
    return $ret;
  }
  
  public static function sendMail($qui,$objet,$corps){
    $pars     = array('qui'=>'','objet'=>'','corp'=>'');

/*    
	$headers[]="MIME-Version: 1.0"; 
	$headers[]="From: webmaster@association-lolita.com";
	$headers[]="From: webmaster@association-lolita.com";
	$headers[]="Reply-To: webmaster@association-lolita.com";
	$headers[]="Bcc: webmaster@association-lolita.com";
	$headers[]='Content-Type: text/html; charset="iso-8859-1"';
	$headers[]='Content-Transfer-Encoding: 8bit';		
*/
		$headers[]= "MIME-Version: 1.0";
		$headers[]= "Content-type: text/html; charset=utf-8";
		$headers[]= "From: webmaster@association-lolita.com <associatws@60gp.ovh.net>";
		$headers[]= "X-Sender: <www.association-lolita.com>";
		$headers[]= "X-Mailer: PHP";
		$headers[]= "X-auth-smtp-user: webmaster@association-lolita.com";
		$headers[]= "X-abuse-contact: webmaster@association-lolita.com";
		$headers[]= "Reply-to:webmaster@association-lolita.com";	 
		$headers[]= "Bcc: webmaster@association-lolita.com";
	
    if(!is_array($qui)){
      $pars['qui']    = $qui;
      $pars['objet']  = $objet;
      $pars['corps']  = $corps;
    } else {
      $pars = array_merge($pars,$qui);
    }
    
    if(isset($pars['headers'])){
      if(!is_array($pars['headers'])){
        $pars['headers'] = array($pars['headers']);
      }
      $headers = array_merge($headers,$pars['headers']);
    }


		
    
		$headers = join("\n",$headers);
    
    if(!self::isLocal()){
      try{
        mail($pars['qui'],$pars['objet'],$pars['corps'],$headers);
      } catch(Exception $e){
        throw new Exception($e->getMessage());
      }
    } else {
      ob_start();
      ?>
<ul class="debug">
  <li>A qui : <?= $pars['qui']?></li>
  <li>Objet : <?= $pars['objet']?></li>
  <li>Message : <pre><?= $pars['corps']?></pre></li>
  <li>Headers : <?= $headers?></li>
</ul>
      <?php
      $ret = ob_get_flush();
      debug::log($ret);
    }
  }
  
}

